<template>
  <div class="search-div">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="关键字:">
        <el-input
          v-model="formInline.keyword"
          placeholder="用户名,姓名,手机号码"
        />
      </el-form-item>
      <el-form-item>
        <div class="inline">
          <span class="demonstration">创建时间:</span>
          <el-date-picker
            v-model="formInline.fromDate"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
    <el-button type="success" @click="dialogFormVisible = true,showPassowrdInput = true">添加</el-button>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column label="用户名" width="180">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.row.userName }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="姓名" width="180">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.row.name }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="手机号" width="160">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.row.phone }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="头像" width="160">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">
            <div class="demo-image">
              <div class="block"  :key="fit">
                <span class="demonstration"></span>
                <el-image
                    style="width: 50px; height: 50px"
                    :src="scope.row.avatar"
                    fit="fit"></el-image>
              </div>
            </div>


            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="描述" width="160">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.row.description }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="150">
        <template #default="scope">
          <div style="display: flex; align-items: center">

            <span style="margin-left: 10px">{{ scope.row.status ==1?"正常":"停用" }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" width="160">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <el-icon>
              <timer />
            </el-icon>
            <span style="margin-left: 10px">{{ scope.row.createTime }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click=";(dialogFormVisible = true), showPassowrdInput = false,handleEdit(scope.row)"
          >
            修改
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="centerDialogVisible = true, handleDelete(scope.row)"
          >
            删除
          </el-button>
          <el-button
              size="small"
              type="warning"
              @click="distributionRole(scope.row),roleFromVisible = true"
          >
            分配权限
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="demo-pagination-block">
      <hr />
      <el-pagination
        v-model:current-page="formInline.pageNum"
        v-model:page-size="formInline.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!--    dialog-->
    <el-dialog v-model="dialogFormVisible" title="添加或修改用户" width="500px">
      <el-form :model="sysUser">
        <el-form-item label="账号" :label-width="100">
          <el-input v-model="sysUser.userName" autocomplete="off" />
        </el-form-item>

        <el-form-item   v-if="showPassowrdInput" label="密码"   placeholder="123" :label-width="100">
          <el-input   v-model="sysUser.password" autocomplete="off" />
        </el-form-item>

        <el-form-item label="姓名" :label-width="100">
          <el-input v-model="sysUser.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="手机号" :label-width="100">
          <el-input v-model="sysUser.phone" autocomplete="off" />
        </el-form-item>
        <el-form-item label="头像" :label-width="100">
          <el-upload
              class="avatar-uploader"
              :action = "upLoadUrl"
              :headers="headers"
              :name = "file"
              method="post"
              :show-file-list="false"
              :auto-upload="true"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
          >
            <img v-if="sysUser.avatar" :src="sysUser.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
<!--          <el-input v-model="sysUser.avatar" autocomplete="off" />-->


        </el-form-item>
        <el-form-item label="描述" :label-width="100">
          <el-input v-model="sysUser.description" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click=";(dialogFormVisible = false), submitForm()"
          >
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>

<!--  确实是否删除-->
  <el-dialog
      v-model="centerDialogVisible"
      title="警告"
      width="500"
      align-center
  >
    <span>确定是否删除</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="centerDialogVisible = false,deleteSubmit()">
          删除
        </el-button>
      </div>
    </template>
  </el-dialog>
<!--  分配权限-->
  <el-dialog v-model="roleFromVisible" title="权限分配" width="40%">
    <el-form label-width="80">
      <el-form-item label="用户名">
       <el-input disabled :value="sysUser.userName" autocomplete="off" />
      </el-form-item>
      <el-form-item label="角色列表">
        <el-checkbox-group
            v-model="checkRoleIds">
          <el-checkbox v-for="role in allRoles" :key="role.id" :label="role.id" :value="role.id">
            {{ role.roleName }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="roleFromVisible = false">取消</el-button>
        <el-button type="primary" @click="roleFromVisible = false,submitDistrubuteRole()">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { onMounted, ref } from 'vue'
import { Timer } from '@element-plus/icons-vue'
import {getUserByPage,addSysUser,modifySysUser,deleteSysRoleSysUser,assignRoleToUser,getRoleIdsByUserId} from "@/api/sysUser";
import {getAllRole} from '@/api/sysRole'
import {ElMessage} from "element-plus";
import {useApp} from "@/pinia/modules/app";
import {baseURL} from "@/utils/request";

const backendUrl = ref(baseURL)
const upLoadUrl = backendUrl.value+"/admin/uploadFile/avatar";
const roleFromVisible = ref(false)
const allRoles= ref([
  {id:1,roleName:"管理员"},
  {id:1,roleName:"经理"}
])
const checkRoleIds = ref([])


const headers = ref(
    {
    token: useApp().authorization.token
    }
)
const centerDialogVisible = ref(false)
const sysUser = ref({
  id: '',
  userName: '',
  password: '',
  name: '',
  phone: '',
  avatar: '',
  description: '',
})
const fetchTableData =()=>{
  getUserByPage(formInline.value).then(response => {
    tableData.value = response.data.list
    total.value = response.data.total
  })
}
const submitDistrubuteRole= ()=>{

  let queryDto  = {userId:sysUser.value.id, roleIdList:checkRoleIds.value}
  console.log(123)
  assignRoleToUser(queryDto).then(response => {
    ElMessage.success(response.message)
  })

}
const resetSysUser  = ()=>{
  Object.keys(sysUser.value).forEach((key)=>{
    sysUser.value[key] = ''
  })
}
//查询提交按钮
let onSubmit = ()=>{
  fetchTableData()
}
//dialog提交
const submitForm =()=>{

  if (sysUser.value.id == ""){
    addSysUser(sysUser.value).then(res=>{
      ElMessage.success(res.message)
      fetchTableData()
      resetSysUser()
    })
  }else {
    console.log(111)
    modifySysUser(sysUser.value).then(res=>{
      ElMessage.success(res.message)
      fetchTableData()
      resetSysUser()
    })
  }
}
let tableData = ref([
  {
    userName: '',
    name: '',
    phone: '',
    avatar: '',
    description: '',
    status: '',
    createTime: '',
  },
])


const total = ref(0)
const formInline = ref({
  keyword: '',
  fromDate: '',
  pageNum: 1,
  pageSize: 10,
})
const dialogFormVisible = ref(false)

const showPassowrdInput = ref(false)
const pickerOptions = ref({
  shortcuts: [
    {
      text: '最近一周',
      onClick(picker) {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
        picker.$emit('pick', [start, end])
      },
    },
    {
      text: '最近一个月',
      onClick(picker) {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
        picker.$emit('pick', [start, end])
      },
    },
    {
      text: '最近三个月',
      onClick(picker) {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
        picker.$emit('pick', [start, end])
      },
    },
  ],
})
const fromDate = ref('')
const distributionRole =(row)=>{
  sysUser.value.id = row.id
  sysUser.value.userName = row.userName
  getAllRole().then(res=>{
    allRoles.value = res.data
  })
  //回填数据
  setCheckRoleIds( sysUser.value.id);
}
//查询选择用户的角色回填入checkRoleIds;
const setCheckRoleIds = (id)=>{
  getRoleIdsByUserId(id).then(res=>{
    checkRoleIds.value = res.data
  })
}

const handleSizeChange =()=>{
  fetchTableData()
}
const handleCurrentChange = ()=>{
  fetchTableData()
}
const resetForm = ()=>{
  Object.keys(sysUser.value).forEach((key)=>{
    sysUser.value[key] = ''
  })
}


const handleEdit = (row)=>{
  sysUser.value.id = row.id
  sysUser.value.userName = row.userName
  sysUser.value.name = row.name
  sysUser.value.phone = row.phone
  sysUser.value.avatar = row.avatar
  sysUser.value.description = row.description
  sysUser.value.password = ''
}
const handleDelete = (row)=>{
  sysUser.value.id = row.id
}

const deleteSubmit = ()=>{
  deleteSysRoleSysUser(sysUser.value).then(res=>{
    ElMessage.success(res.message)
    resetSysUser()
    fetchTableData()
  })
}

//头像上传前的检擦
const beforeAvatarUpload =(rawFile)=>{
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}
//上传成功后的回调
const  handleAvatarSuccess = (response)=> {
  sysUser.value.avatar =  response.data;
}




onMounted(()=>{
  fetchTableData()
})
</script>
<style scoped lang="scss">
.inline {
  display: inline-block;
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

.search-div {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

</style>
